package tinynio;

import java.io.IOException;
import java.net.InetSocketAddress;

public class Application {
	public static enum EndPoint {
		SERVER, CLIENT
	}

	private Communicator communicator;
	private SelectGroup group;

	public Application(EndPoint endPoint) throws IOException {
		group = new SelectGroup();
		createCommunicator(endPoint);
	}

	private void createCommunicator(EndPoint endPoint) throws IOException {
		if (endPoint == EndPoint.SERVER) {
			communicator = new ServerSocketCommunicator(group.next());
			return;
		}
		if (endPoint == EndPoint.CLIENT) {
			communicator = new SocketCommunicator(group.next());
			return;
		}

		throw new IllegalArgumentException("endpoint is error");
	}

	public Application config(Configuration config) {
		communicator.config(config);
		return this;
	}

	public Application bind(int port) throws IOException {
		communicator.bind(new InetSocketAddress(port));
		return this;
	}

	public Application connect(String hostname, int port) throws IOException {
		communicator.connect(new InetSocketAddress(hostname, port));
		return this;
	}
}
